<template>
  <div class="main commodity-manage-list">
    <div class="filter-container">
      <el-input @keyup.enter.native="search" class="filter-item" placeholder="按商品名称搜索" v-model="listQuery.name" clearable></el-input>
      <el-select   class="filter-item" v-model="listQuery.categoryId" :loading="categoryLoading" placeholder="商品大类" filterable clearable>
        <el-option v-for="(item, index) of categoryTree" :style="{paddingLeft: `${item._level * 15}px`}" :key="index" :label="`${item.parentId ? '∟' : ''}${item.name}`" :value="item.id"></el-option>
      </el-select>
      <el-select v-model="listQuery.upshelf" class="filter-item" placeholder="商品状态" filterable clearable>
        <el-option  label="上架" :value="1"></el-option>
        <el-option  label="下架" :value="0"></el-option>
      </el-select>
      <el-select v-model="listQuery.businessModel" class="filter-item" placeholder="经营模式" filterable clearable>
        <el-option :key="1" label="自营" :value="1"></el-option>
        <el-option :key="2" label="招商" :value="2"></el-option>
      </el-select>
      <!--<el-select v-if="$store.getters.organizationId===1 && goodsType===1" v-model="listQuery.organizationId" class="filter-item" placeholder="请选择商家" filterable clearable>
          <el-option v-for="item in organizations" :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select>-->
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
      <!--<el-button class="filter-item" type="success" :loading="refreshLoading" @click="updateData" plain>刷新数据</el-button>
      <router-link :to="{name: $store.getters.organizationId===1&&goodsType===2?'commodityPreManageAdd':'commodityManageAdd', query: {goodsType: $store.getters.organizationId===1 ? goodsType : 2}}" class="filter-item">
          <el-button type="success" icon="el-icon-plus">新建</el-button>
      </router-link>-->
    </div>
    <div style="padding: 6px; background: #fff; text-align:right">
      <el-button v-if="rightsButtons['export']" type="primary" @click="exportSearch" :loading="exportLoading" plain>导出查询结果</el-button>
    </div>
    <el-table
      :data="list"
      v-loading="listLoading"
      element-loading-text="给我一点时间"
      border
      highlight-current-row
    >
      <el-table-column align="center" label="款号" width="110">
        <template slot-scope="scope">
          <span>{{scope.row.serialNo}}</span>
        </template>
      </el-table-column>
      <el-table-column align="left" label="商品名称" min-width="110">
        <template slot-scope="scope">
          <a
            style="color: #409eff"
            target="_blank"
            :href="getUrl({id: scope.row.goodsId, fromType: 1, goodsType: 1, activityId: '', packType: ''})"
          >{{scope.row.name}}</a>
        </template>
      </el-table-column>
      <el-table-column align="center" label="分类">
        <template slot-scope="scope">
          <span>{{scope.row.categoryName}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" width="150">
        <template slot-scope="scope">
          <span v-if="scope.row.upshelf" style="color: green">已上架</span>
          <span v-else style="color: #9b9b9b">已下架</span>
        </template>
        <!--<template slot-scope="scope">
                <el-switch
                    v-model="scope.row.upshelf"
                    @change="updateStatus(scope.row)"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    active-text="上架"
                    inactive-text="下架"
                    :active-value="1"
                    :inactive-value="0">
                </el-switch>
        </template>-->
      </el-table-column>
      <el-table-column align="center" label="是否售卖" width="100">
        <template slot-scope="scope">
          <span>{{scope.row.isSell == 1 ? '是' : '否'}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="业务首次上架时间" width="100">
        <template slot-scope="scope">
          <span>{{formatDate(scope.row.firstUpSelfTime)}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="150">
        <template slot-scope="scope">
          <span>{{formatDate(scope.row.createdAt)}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="160" v-if="rightsButtons['view'] || rightsButtons['edit']">
        <template slot-scope="scope">
          <router-link v-if="rightsButtons['view']" :to="{name: $store.getters.organizationId===1&&goodsType==2?'commodityPreManageView':'commodityManageView', params: {id: scope.row.id}, query: {goodsType: $store.getters.organizationId===1 ? goodsType : 2, goodsId: scope.row.goodsId, pageType: 'view'}}">
            <el-button type="success" size="mini" plain>查看</el-button>
          </router-link>
          <router-link
            v-if="!scope.row.upshelf && rightsButtons['edit']"
            :to="{name: $store.getters.organizationId===1&&goodsType==2?'commodityPreManageEdit':'commodityManageEdit', params: {id: scope.row.id}, query: {goodsType: $store.getters.organizationId===1 ? goodsType : 2, goodsId: scope.row.goodsId, pageType: 'edit'}}"
          >
            <el-button type="primary" size="mini" plain>编辑</el-button>
          </router-link>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container" v-if="total > 0">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page.sync="listQuery.pageIndex"
        :page-size="listQuery.pageSize"
        :total="total"
        layout="total, prev, pager, next, jumper"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import { getCategoryTree } from "../../../api/common"
import treeToArray from '@/components/TreeTable/eval'
export default {
  name: "commodityManage",
  props: {
    goodsType: { default: 1 }
  },
  data() {
    return {
      parentCategory: [],
      refreshLoading: false,

      organizations: [],
      list: [],
      listQuery: {
        userId: this.$store.getters.userId,
        organizationId: "",
        categoryId: "",
        businessModel: "",
        goodsType: 1,
        name: "",
        pageIndex: 1,
        pageSize: 20,
        upshelf:''
      },
      categoryTree: [],
      total: 0,
      listLoading: false,
      exportLoading: false,
      categoryLoading: true
    };
  },
  watch: {
    $route() {
      this.listQuery.organizationId = "";
      this.getList();
      this.getCategory();
      this.getOrganizations();
    }
  },
  created() {
    // this.listQuery = this.getLocalQuery(this.listQuery, 'commodity');
    this.getList();
    this.getCategory();
    this.getOrganizations();
  },
  methods: {
    // 获取列表
    getList() {
      this.listLoading = true;
      this.listQuery.goodsType =
        this.$store.getters.organizationId === 1 ? this.goodsType : 2;
      if (this.$store.getters.organizationId !== 1) {
        this.listQuery.organizationId = this.$store.getters.organizationId;
      }
      if (this.$store.getters.organizationId === 1 && this.goodsType === 2) {
        this.listQuery.organizationId = 1;
      }

      this.setLocalQuery(this.listQuery, "commodity");
      this.request({
        url: "/bsnl-product/goods/query",
        method: "post",
        data: this.listQuery
      })
        .then(({ data, totalCount }) => {
          this.list = data;
          this.total = totalCount;
          this.listLoading = false;
        })
        .catch(err => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    // 获取分类列表
    getCategory() {
      // this.request({
      //   url: "/bsnl-product/category/getFirstCategory",
      //   method: "post",
      //   data: {}
      // }).then(({ data2 }) => {
      //     this.parentCategory = data2;
      //   })
      //   .catch(err => {
      //     this.parentCategory = [];
      //   });
       getCategoryTree().then(({data}) => {
        let tmp = data ? data : [];
        this.categoryTree = treeToArray(tmp, {
          type: Boolean,
          default: false
        });
        this.categoryLoading = false
      }).catch(err => {
        this.categoryTree = [];
        this.categoryLoading = false
      }); 
    },
    // 获取商家列表
    getOrganizations() {
      this.request({
        url: "/bsnl-authority/organization/tree",
        method: "get",
        params: {}
      })
        .then(({ data }) => {
          this.organizations = data;
        })
        .catch(err => {
          this.organizations = [];
        });
    },
    // 上架/下架
    updateStatus({ id, upshelf, isSell }) {
      this.$confirm(`确定${upshelf ? "下架" : "上架"}该商品`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.request({
            url: "/bsnl-product/goods/status",
            method: "post",
            data: {
              id,
              upshelf: !upshelf ? 1 : 0,
              isSell: (!upshelf ? 1 : 0) && isSell
            }
          })
            .then(() => {
              this.$message.success(upshelf === 1 ? "下架成功" : "上架成功");
              this.getList();
            })
            .catch(err => {
              this.$message.error(err);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作"
          });
        });
    },
    // 重设缓存
    resetCache(item) {
      this.$confirm(`确定要重设 ${item.name} 的缓存吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$message.success("重设缓存成功");
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 搜索
    search() {
      this.listQuery.pageIndex = 1;
      this.getList();
    },
    // 切换分页
    handleCurrentChange(page) {
      this.listQuery.pageIndex = page;
      this.getList();
    },
    // 刷新数据
    updateData() {
      this.refreshLoading = true;
      this.request({
        //url: `/bsnl-erp-product/goodsSku/syncSingeGoodsSkuToApp/${skuCode}`,
        url: `http://172.16.8.162:8080/erp/bsnl/getGoods`,
        method: "post"
      })
        .then(response => {
          console.log(response);
          this.refreshLoading = false;
          this.$message.success("数据刷新成功");
          this.getList();
        })
        .catch(err => {
          console.log(err);
          this.refreshLoading = false;
        });
    },
    // 导出搜索结果
    exportSearch() {
      this.exportLoading = true
      this.request({
        url: "/bsnl-product/goods/attr/exportExcel",
        method: "post",
        data: this.listQuery,
        headers: {
          authorKey: `${this.$route.name}Export`
        },
        responseType: 'blob'
      }).then(res => {
          this.downloadFile(res)
          this.exportLoading = false
        })
        .catch(err => {
          console.log(err)
          this.exportLoading = false
        });
    }
  }
};
</script>
